<?php
declare(strict_types=1);

namespace ExpressionEngine\LoopEngine;

use ExpressionEngine\ExpressionLogic;
use ExpressionEngine\LoopEngine\Enum\LoopEnum;
use ExpressionEngine\LoopEngine\Loop\LoopInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;

class LoopEngine implements LoopEngineInterface
{
    protected ContainerInterface $container;
    protected ExpressionLogic $expressionLogic;

    public function __construct(ContainerInterface $container, ExpressionLogic $expressionLogic)
    {
        $this->container = $container;
        $this->expressionLogic = $expressionLogic;
    }

    public function compile(array $loopItem, array $context): mixed
    {
        $result = true;
        foreach (LoopEnum::COMPILE_LOOP_LIST as $loopClass) {
            /** @var LoopInterface $loopInstance */
            $loopInstance = $this->container->get($loopClass);
            if ($loopInstance->is($loopItem)) {
                $result = $loopInstance->compile($loopItem, $context);
            }
            break;
        }
        return $result;
    }

    public function compileList(array $loopList, array $context, array $compileContext): mixed
    {
        foreach ($loopList as $key => $loopItem) {
            $compileContext[$key] = $this->compile($loopItem, $context);
        }
        return $compileContext;
    }
}